package com.fishing.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;

import QL.ButlerAgentCountStatRequest;
import QL.ButlerAgentCountStatResponse;
import QL.ButlerAgentPopularizeUrlRequest;
import QL.ButlerAgentPopularizeUrlResponse;
import QL.ButlerAgentQuerySubUsersContributionLogRequest;
import QL.ButlerAgentQuerySubUsersContributionLogResponse;
import QL.ButlerAgentQuerySubUsersDetailRequest;
import QL.ButlerAgentQuerySubUsersDetailResponse;
import QL.ButlerAgentQuerySubUsersRequest;
import QL.ButlerAgentQuerySubUsersResponse;
import QL.ButlerAgentUserInfo;
import QL.ButlerAgentWarheadExchangeCountStatRequest;
import QL.ButlerAgentWarheadExchangeCountStatResponse;
import QL.ButlerAgentWarheadExchangeLogRequest;
import QL.ButlerAgentWarheadExchangeLogResponse;
import QL.ButlerExcelFieldGetRequest;
import QL.ButlerExcelFieldGetResponse;
import QL.ButlerExcelFieldSetRequest;
import QL.ButlerExcelFieldSetResponse;
import QL.QLClient;
import net.sf.json.JSONObject;


/**
 * 全民代理
 * @author lrz
 * */
@Controller
public class AgentController {
    
	private static QLClient client = new QLClient();
	
	@RequestMapping("agent/information")
	public ModelAndView information(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/information");
		return mav;
	}
	
	@RequestMapping("agent/toList")
	public ModelAndView toList(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/list");
		return mav;
	}
	
	@RequestMapping("agent/exchangeNumber")
	public ModelAndView exchangeNumber(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/exchangeNumber");
		return mav;
	}
	
	@RequestMapping("agent/record")
	public ModelAndView record(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/record");
		return mav;
	}
	
	@RequestMapping("agent/contributionquery")
	public ModelAndView contributionquery(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/contributionquery");
		return mav;
	}
	
	@RequestMapping("agent/nextcontributionquery")
	public ModelAndView nextcontributionquery(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/nextcontributionquery");
		return mav;
	}
	
	//region 跳转返还比例页面
	@RequestMapping("agent/feedBackSettingView")
	public ModelAndView feedBackSettingView(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("agent/feedBackSettingView");
		return mav;
	}
	//endregion
	
	@ResponseBody
	@RequestMapping(value="agent/List",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map List(HttpServletRequest request,String UserId)throws Exception{
		ButlerAgentQuerySubUsersRequest req = new ButlerAgentQuerySubUsersRequest();
		ButlerAgentQuerySubUsersResponse rsp = new ButlerAgentQuerySubUsersResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			if (("").equals(UserId))
				req.ParentUserId = 0;
			else 
				req.ParentUserId = Integer.parseInt(UserId);
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		for(int i = 0;i < rsp.AgentUserList.size(); i++) {
			rsp.AgentUserList.get(i).Assets = rsp.AgentUserList.get(i).Assets/100;
			rsp.AgentUserList.get(i).TotalAssets = rsp.AgentUserList.get(i).TotalAssets/100;
		}
		map.put("status", "200");
		map.put("message", "");
		map.put("data", rsp.AgentUserList);
		map.put("count", rsp.AgentUserList.size());
		return map;
	}
	
	
	@ResponseBody
	@RequestMapping(value="agent/Information",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map Information(HttpServletRequest request)throws Exception{
		ButlerAgentPopularizeUrlRequest req = new ButlerAgentPopularizeUrlRequest();
		ButlerAgentPopularizeUrlResponse rsp = new ButlerAgentPopularizeUrlResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		ArrayList list = new ArrayList();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject  json = new JSONObject();
		json.put("PopularizeUrl", rsp.PopularizeUrl);
		list.add(json);
		map.put("status", "200");
		map.put("message", "");
		map.put("data", list);
		map.put("count", list.size());
		return map;
	}
	
	@ResponseBody
	@RequestMapping(value="agent/CountStat",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map CountStat(HttpServletRequest request)throws Exception{
		ButlerAgentCountStatRequest req = new ButlerAgentCountStatRequest();
		ButlerAgentCountStatResponse rsp = new ButlerAgentCountStatResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		ArrayList list = new ArrayList();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(rsp.Result != null) {
			String[] str = rsp.Result.split("\\|");
			for(int i = 0;i < str.length;i++) {
				Map<String,Object> data = new HashMap<>();
				String[] strs2 = str[i].split(",");
				for(int  j = 0;j < strs2.length;j++) {
					if(j == 0) data.put("Level", strs2[j]);
					if(j == 1) data.put("Number", strs2[j]);
				}
				list.add(data);
			}
		}
		map.put("status", "200");
		map.put("message", "");
		map.put("data", list);
		map.put("count", list.size());
		return map;
	}
	
	@ResponseBody
	@RequestMapping(value="agent/ExchangeNumber",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map ExchangeNumber(HttpServletRequest request,String PageIndex,String PageCount)throws Exception{
		ButlerAgentWarheadExchangeCountStatRequest req = new ButlerAgentWarheadExchangeCountStatRequest();
		ButlerAgentWarheadExchangeCountStatResponse rsp = new ButlerAgentWarheadExchangeCountStatResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			req.PageIndex = Integer.parseInt(PageIndex) - 1;
			req.PageCount = Integer.parseInt(PageCount);
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("status", "200");
		map.put("message", "");
		map.put("data", rsp.ResultList);
		map.put("count", rsp.ResultList.size());
		return map;
	}
	
	@ResponseBody
	@RequestMapping(value="agent/Record",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map Record(HttpServletRequest request,String pageIndex,String pageCount,String UserId)throws Exception{
		ButlerAgentWarheadExchangeLogRequest req = new ButlerAgentWarheadExchangeLogRequest();
		ButlerAgentWarheadExchangeLogResponse rsp = new ButlerAgentWarheadExchangeLogResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			req.PageIndex = Integer.parseInt(pageIndex) - 1;
			req.PageCount = Integer.parseInt(pageCount);
			if(("").equals(UserId))
				req.UserId = 0;
			else
				req.UserId = Integer.parseInt(UserId);
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("status", "200");
		map.put("message", "");
		if(rsp.ResultList == null)
			map.put("data", 0);
		else
			map.put("data", rsp.ResultList);
		map.put("count", rsp.TotalCount);
		return map;
	}
	
	//代理信息详细查询 
	@ResponseBody
	@RequestMapping(value="agent/Detailquery",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map Detailquery(HttpServletRequest request,String PageIndex,String PageCount,String UserId)throws Exception{
		ButlerAgentQuerySubUsersDetailRequest req = new ButlerAgentQuerySubUsersDetailRequest();
		ButlerAgentQuerySubUsersDetailResponse rsp = new ButlerAgentQuerySubUsersDetailResponse();
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			req.PageIndex = Integer.parseInt(PageIndex) - 1;
			req.PageCount = Integer.parseInt(PageCount);
			if(("").equals(UserId)) {
				map.put("status", "200");
				map.put("message", "");
				map.put("data", 0);
				map.put("count", 0);
				return map;
			}
			else
				req.UserId = Integer.parseInt(UserId);
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		for(int i = 0;i < rsp.ResultList.size(); i++) {
			rsp.ResultList.get(i).TotalContribution = rsp.ResultList.get(i).TotalContribution/100;
			rsp.ResultList.get(i).TodayContribution = rsp.ResultList.get(i).TodayContribution/100;
			rsp.ResultList.get(i).TodayRecharge = rsp.ResultList.get(i).TodayRecharge/100;
			rsp.ResultList.get(i).TotalRecharge = rsp.ResultList.get(i).TotalRecharge/100;
		}
		
		map.put("status", "200");
		map.put("message", "");
		map.put("data", rsp.ResultList);
		map.put("count", rsp.TotalCount);
		return map;
	}
	
	    //贡献详细查询 
		@ResponseBody
		@RequestMapping(value="agent/contributiondetailquery",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
		public Map contributiondetailquery(HttpServletRequest request,String PageIndex,String PageCount,String UserId,String NextUserId)throws Exception{
			ButlerAgentQuerySubUsersContributionLogRequest req = new ButlerAgentQuerySubUsersContributionLogRequest();
			ButlerAgentQuerySubUsersContributionLogResponse rsp = new ButlerAgentQuerySubUsersContributionLogResponse();
			Map<String,Object> map = new HashMap<String,Object>();
			try {
				req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
				req.PageIndex = Integer.parseInt(PageIndex) - 1;
				req.PageCount = Integer.parseInt(PageCount);
				if(("").equals(UserId)) {
					map.put("status", "200");
					map.put("message", "");
					map.put("data", 0);
					map.put("count", 0);
					return map;
				}
				else
					req.UserId = Integer.parseInt(UserId);
				if (("").equals(NextUserId))
					req.SubUserId = 0;
				else 
					req.SubUserId = Integer.parseInt(NextUserId);
				if (req.ZoneId < 0)
					client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
				client.Execute(req, rsp);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			for(int i = 0;i < rsp.ResultList.size(); i++) {
				rsp.ResultList.get(i).Contribution = rsp.ResultList.get(i).Contribution/100;
				rsp.ResultList.get(i).RechargeAmount = rsp.ResultList.get(i).RechargeAmount/100;
			}
			
			map.put("status", "200");
			map.put("message", "");
			map.put("data", rsp.ResultList);
			map.put("count", rsp.TotalCount);
			return map;
		}
		
		//查询返还比例,返回客户端
		@ResponseBody
		@RequestMapping(value="agent/feedBackSetting",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
		public JSONObject feedBackSetting(HttpServletRequest request) {
			JSONObject json = new JSONObject();
			ButlerExcelFieldGetRequest req = new ButlerExcelFieldGetRequest();
			ButlerExcelFieldGetResponse rsp = new ButlerExcelFieldGetResponse();
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			String str = "[[\"Platform/Global.xlsx\",1,\"AgentFeedbackSetting\"]]";
			req.FieldString = str;
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
			if (rsp.ErrMsg == null) {
				JSONArray arry = new JSONArray();
				arry = (JSONArray) JSONArray.parse(rsp.Content);
				arry = (JSONArray) JSONArray.parse(arry.get(0).toString());
				for (int i = 0;i < arry.size();i++) {
					json.put("agent"+i, Math.round(Float.parseFloat(arry.get(i).toString().split(",")[1]) * 100));
				}
				JSONObject jsondata = new JSONObject();
				jsondata.put("status", "200");
				jsondata.put("message", "success");
				jsondata.put("data", "[" + json + "]");
				jsondata.put("count", json.toString().split(",").length);
				arry = null;
				req = null;
				rsp = null;
				return jsondata;
			}else {
				json.put("status", "201");
				json.put("message", rsp.ErrMsg);
				req = null;
				rsp = null;
				return json;
			}
        }
		
		//region 设置斗地主代理返还比例
		@ResponseBody
		@RequestMapping(value="game/ddzFeedBackSetting",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
		public JSONObject ddzFeedBackSetting(HttpServletRequest request,@RequestBody JSONObject agentFeedBack)  throws Exception {
			ButlerExcelFieldSetRequest req = new ButlerExcelFieldSetRequest();
			ButlerExcelFieldSetResponse rsp = new ButlerExcelFieldSetResponse();
			JSONObject json = new JSONObject();
			StringBuilder sb = new StringBuilder();
			
			sb.append("[");
			Iterator iter = agentFeedBack.entrySet().iterator();
			while(iter.hasNext()) {
				Map.Entry strMap = (Map.Entry)iter.next();
				sb.append("[");
				sb.append(Float.parseFloat(strMap.getValue().toString())/100);
				sb.append(",");
				sb.append(Float.parseFloat(strMap.getValue().toString())/100);
				sb.append(",");
				sb.append(Float.parseFloat(strMap.getValue().toString())/100);
				sb.append("]");
				if (iter.hasNext())
					sb.append(",");
				else
					sb.append("]");
			}
			
			req.ZoneId = (Integer) request.getSession().getAttribute("ZoneId");
			req.FieldString = "[[\"Platform/Global.xlsx\",1,\"AgentFeedbackSetting\",\"" + sb.toString() +  "\"]]";
			if (req.ZoneId < 0)
				client.ServerUrl = "http://api2.qq1798.com:8000/router/rest";
			client.Execute(req, rsp);
			
			if(rsp.ErrMsg == null) {
				json.put("status", "200");
				json.put("message", "success");
				return json;
			}else {
				json.put("status", "201");
				json.put("message", rsp.ErrMsg);
				return json;
			}
		}
		//endregion
}
